package com.edais.service.imp;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.CenterDao;
import com.edais.dao.PayDao;
import com.edais.domain.Bank;
import com.edais.domain.Finance;
import com.edais.domain.OrderFormRecharge;
import com.edais.domain.User;
import com.edais.domain.UserInfo;
import com.edais.domain.zftPay.FastPayTokenParamters;
import com.edais.domain.zftPay.PayParamtersTemp;
import com.edais.domain.zftPay.RechargeTokenParamters;
import com.edais.service.CenterService;
import com.edais.service.PayService;
import com.edais.service.UserService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.Message;
import com.edais.util.StrUtil;
import com.edais.util.ThirdPartyEnvUtil;
import com.edais.util.RSAThirdParty.RSA;
import com.edais.util.zftPay.ZftPayEnvUtil;
import com.edais.vo.UserBankCardVo;

@Service

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class PayServiceImp implements PayService {
	private static final Log logger = LogFactory.getLog(PayServiceImp.class);

	@Autowired
	private CenterService centerService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private CenterDao centerDao;
	
	@Autowired
	private PayDao payDao;

	@Override
	public Map<String, String> fastPayTokenCheckData(Map<String, String> map)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();

		// 用户id
		String userId = map.get("userId");
		// 交易金额(元)
		String txAmt = map.get("buyAmount");
		// 手机号
//		String mobileNo = map.get("mobileNo");
		// 购买的理财计划id
		String financeId = map.get("financeID");
		// 绑定银行卡id
		String backCardId = map.get("backCardId");
		// 是否使用余额购买(Y/N)
		String isUseBalance = map.get("isUseBalance");
		// 资金流转方式
		String cycleMatchType = map.get("cycleMatchType");
		// 邀请码(可为空)
		String invitationCd = map.get("invitationCd");

		// 程序必须参数未传入
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(financeId)
				|| StringUtils.isBlank(isUseBalance)
				|| StringUtils.isBlank(cycleMatchType)
				|| StringUtils.isBlank(backCardId)) {
			result.put("code", Consts.ERROR_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return result;
		}

		// 获取购买的产品是否在预售期内
		String checkResult = centerService.checkPlanSellTime(financeId);
		if (!"true".equals(checkResult)) {
			String msgCn;
			if ("buy.has.not.started".equals(checkResult)) {
				msgCn = Message.CnDescriptionExpression.BUY_HAS_NOT_STARTED;
			} else if ("buy.has.ended".equals(checkResult)) {
				msgCn = Message.CnDescriptionExpression.BUY_HAS_ENDED;
			} else {
				msgCn = Message.CnDescriptionExpression.PLAN_HAS_NOT_OPENED;
			}
			result.put("code", Consts.CHECK_CODE);
			result.put("message", msgCn);
			return result;
		}

		// 购买金额未输入
		if (StringUtils.isBlank(txAmt)) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.AMOUNT_IS_NULL);
			return result;
		}

		// 银行预留手机号未输入
//		if (StringUtils.isBlank(mobileNo)) {
//			result.put("code", Consts.CHECK_CODE);
//			result.put("message",
//					Message.CnDescriptionExpression.MOBILE_IS_NULL);
//			return result;
//		}
		
		// 银行预留手机号合法检查
//		boolean mobileCheck = mobileNo.matches(Consts.PHONECHECK2);
//		if (!mobileCheck) {
//			result.put("code", Consts.CHECK_CODE);
//			result.put("message",
//					Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
//			return result;
//		}

		// 购买金额检查（必须是1元以上）
		boolean flag = txAmt.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			// 输入的值为非法字符
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_NON_STANDARD);
			return result;
		}

		BigDecimal decBuyAmount = new BigDecimal(txAmt);// 购买金额

		// 投资金额的上下限检查
		Finance finance = centerService.getFinanceplanDetail(financeId, "");
		BigDecimal minInvestMoney = finance.getMin_buyer_amount();// 最小购买金额
		BigDecimal maxBuyerAmount = finance.getMax_buyer_amount();// 最大购买金额

		if (null != minInvestMoney
				&& CommonUtil.checkAmount(decBuyAmount, minInvestMoney) < 0) {
			// 最小投资金额
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_BELOW_MINAMOUNT);
			return result;
		}
		if (null != maxBuyerAmount
				&& CommonUtil.checkAmount(decBuyAmount, maxBuyerAmount) > 0) {
			// 购买最大金额
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_EXCEEDS_MAXAMOUNT);
			return result;
		}

		// 判断用户是否实名认证
		User user = userService.getUserDetail(userId);
		if (!"Y".equals(user.getSina_idcard_validate())
				|| !"1".equals(user.getIs_create_acct())
				|| !"Y".equals(user.getIdcard_validate())) {
			// 没有经过实名认证不能进行购买
			result.put("code", Consts.CHECK_CODE);
			result.put("message",Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
			return result;
		}

		// 邀请码
		if ("Y".equals(finance.getIf_support_invicode())) {
			// 邀请码增加校验
			String s = this.centerService.checkInviteCode(
					invitationCd == null ? "" : invitationCd, userId);
			if ("N".equals(s)) {
				result.put("code", Consts.ERROR_CODE);
				result.put("message",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return result;
			}
		}

		if ("Y".equals(finance.getIf_support_invicode())
				&& !StringUtils.isBlank(invitationCd)
				&& !invitationCd.equalsIgnoreCase(user.getInvitation_code())) {
			/**
			 * 1:输入邀请码的情况下，先判断此邀请码是否存在且非本人 2:如果有效且非本人，则判断被邀请人是否是首次加入“e计划”，
			 */
			int count = this.userService.getUserNotMeByInviteCode(
					invitationCd.toUpperCase(), userId);
			if (count <= 0) {
				// 邀请码不存在
				result.put("code", Consts.CHECK_CODE);
				result.put("message",
						Message.CnDescriptionExpression.INVITATIONCD_NOT_EXIST);
				return result;
			}
		} else if ("Y".equals(finance.getIf_support_invicode())
				&& !StringUtils.isBlank(invitationCd)
				&& invitationCd.equalsIgnoreCase(user.getInvitation_code())) {
			// 本人邀请码
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.PRIVATE_INVITATIONCD);
			return result;
		}

		// 判断是否优先用余额购买
		// 如果选择了使用余额购买，首先先判断余额是否足够购买（余额>=购买理财计划金额），足够的情况下直接就可以购买，不需要通过调用第三方，直接进行购买
		// 如果余额不够（余额<购买理财计划金额）,则银行卡的充值金额=购买理财计划金额-余额，然后调用第三方进行充值。
		// 如果没有选择余额购买，则银行卡的充值金额=购买理财计划金额-余额，然后调用第三方进行充值。
		String acctBalance = "0.00";// 余额
		BigDecimal cardAmount = BigDecimal.ZERO; // 银行卡扣款金额
		BigDecimal decBalance = BigDecimal.ZERO;

		if ("Y".equals(isUseBalance)) {
			// 选择了余额购买
			// 获取该用户的余额
			Map<String, Object> pageMode = new HashMap<String, Object>();
			pageMode.put("userId", userId);

			Map resMap = centerService.getCusBalance(pageMode);
			if (resMap != null && "00000".equals(resMap.get("rescode"))) {
				acctBalance = resMap.get("ACCTBALANCE") + "";
			} else {
				result.put("code", Consts.ERROR_CODE);
				result.put("message",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return result;
			}

			decBalance = new BigDecimal(acctBalance);// 余额

			// 余额-理财计划金额 < 0
			if (decBalance.compareTo(decBuyAmount) < 0) {
				// 余额不足，需要用银行卡购买
				// 计算银行卡需要扣款的金额数
				cardAmount = decBuyAmount.subtract(decBalance);
			} else {
				// 余额足够，无需银行卡
				result.put("code", Consts.ERROR_CODE);
				result.put("message",
						Message.CnDescriptionExpression.BUSINESSE_ERROR);
				return result;
			}
		} else {
			// 没选择余额扣款
			cardAmount = decBuyAmount;
		}
		
		// 银行扣款金额必须大于1.01元
		if (cardAmount.compareTo(BigDecimal.valueOf(1.01)) == -1) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_LESSTHAN_1YUAN);
			return result;
		}

		// 充值金额(分)
		String sum = cardAmount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toPlainString();//金额(元转为分)
		result.put("sum", sum);//购买金额（分）
		result.put("sum_yuan", cardAmount.toPlainString());//购买金额（元）

		result.put("code", Consts.SUCCESS_CODE);
		result.put("message", Consts.SUCCESS_DESCRIBE);
		return result;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String,String> dealZftFastPayToken(Map<String, String> map) throws Exception {
		Map<String,String> resMap = new HashMap<String,String>();
		
		// 用户id
		String userId = map.get("userId");
		// 银行卡id
		String backCardId = map.get("backCardId");

		// 交易金额(分)
//		String txAmt = map.get("txAmt");
		// 交易金额(元)
		String sumYuan = map.get("sum_yuan");
		// 理财计划id
		String planId = map.get("financeID");
		// 投资循环方式
		String cycleMatchType  = map.get("cycleMatchType");
		// 邀请码
		String invitationCode  = map.get("invitationCd");

		// 交易金额(元)
		String buyAmount = map.get("buyAmount");		// 购买计划金额
		
		// 获取交易流水号
		String orderId = centerService.setSeqCycleOrderNo();
		// 获取身份信息
		UserInfo userInfo = userService.getUserInfo(userId);
		// 根据银行卡id取得用户的银行卡信息
		HashMap<String,Object> userPayCdParam = new HashMap<String,Object>();
		userPayCdParam.put("isValid","Y");
		userPayCdParam.put("bankCardId", backCardId);
		userPayCdParam.put("userId", userId);
		userPayCdParam.put("isBinding", "Y");
		UserBankCardVo userRecePayCard =centerService.getRecePayBank(userPayCdParam);
		
		// 银行预留手机号
		map.put("mobileNo", userRecePayCard.getPhone_no());
		
		// 交易时间
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String timeString = dataFormat.format(date);
		//预下单处理	
		map.put("orderId", orderId);//流水号
		map.put("accNo", userRecePayCard.getCard_number());//卡号
		map.put("realName", userInfo.getReal_name());//真实姓名
		map.put("idCardNo", userInfo.getId_card());//身份证号码
		map.put("timeString", timeString);//交易时间
		
		// 请求参数封装
		Map<String, String> payParamMap = new HashMap<String, String>();
		payParamMap.put("tradeOrderId", map.get("orderId"));
		payParamMap.put("txAmt", map.get("txAmt"));
		payParamMap.put("mobileNo", map.get("mobileNo"));
		payParamMap.put("accNo", map.get("accNo"));
		payParamMap.put("realName", map.get("realName"));
		payParamMap.put("idCardNo", map.get("idCardNo"));
		payParamMap.put("timeString", map.get("timeString"));

//		String param = CommonUtil.getHttpParameterFromMap(payParamMap);
//		logger.debug("支付通快捷支付预下单请求参数："+param);
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(payParamMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("payTokenUrl");

		String payTokenResult = CommonUtil.sendPostByHttp(url, requestParam);
		String paramStr = "";
		String fastPayToken = "";
		
		if( null == payTokenResult ){
			logger.error("支付通快捷支付预下单失败");
			throw new RuntimeException("支付预下单失败");
		}else{
			//解析发送结果
			Map payTokenResultMap = JsonUtil.getMapFromJsonString(payTokenResult);
			if(null == payTokenResultMap  || "sysException".equals(payTokenResultMap.get("rescode"))){
				// 系统异常
				logger.error("支付通快捷支付预下单失败:" + String.valueOf(payTokenResultMap.get("resmsg_cn")));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", "支付预下单失败");
				return resMap;
			}else if("BusinessException".equals(payTokenResultMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("支付通快捷支付预下单失败:" + String.valueOf(payTokenResultMap.get("resmsg_cn")));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", String.valueOf(payTokenResultMap.get("resmsg_cn")));
				return resMap;
			}else{
				paramStr = String.valueOf(payTokenResultMap.get("paramStr"));
				fastPayToken = String.valueOf(payTokenResultMap.get("fastPayToken"));
			}
		}
		
		/*Map<String,String> result = doFastPayToken(map);
		if (!Consts.SUCCESS_CODE.equals(result.get("code"))) {
			return result;
		}*/
		
		// 充值订单生成
		OrderFormRecharge orderFormRecharge = new OrderFormRecharge();
		String platform = "ZHIFUTONGPAY";
		orderFormRecharge.setAmount(new BigDecimal(sumYuan));// 订单金额
		orderFormRecharge.setOrderform_id(orderId);// 订单号
		orderFormRecharge.setRecharge_orderform_status("WAIT_BUYER_PAY");// 等待付款
		orderFormRecharge.setUser_id(Integer.parseInt(userId));// 所属用户
		orderFormRecharge.setSend_message(paramStr);// 上送报文
		orderFormRecharge.setRechargetype("01");// 理财人类型
		orderFormRecharge.setAccounttype("01");// 个人主账户
		orderFormRecharge.setCore_status("CORE_WAIT");// 未调用核心，初始化状态
		orderFormRecharge.setRecharge_channel("MOBILE"); //充值渠道（WEB:网站;MOBILE:移动端）
		orderFormRecharge.setRecharge_platform(platform);//充值平台（UPAY:U付;SINAPAY:新浪支付;LIANLIANPAY:连连支付）
		centerDao.createRechargeOrder(orderFormRecharge);
		
		// 购买参数表设置
		FastPayTokenParamters fastPayTokenParamters = new FastPayTokenParamters();
		fastPayTokenParamters.setTradeOrderId(orderId);
		fastPayTokenParamters.setMerNo(ZftPayEnvUtil.getValue("partner_id"));//商户号
		fastPayTokenParamters.setTrDt(timeString);
		fastPayTokenParamters.setFastPayToken(fastPayToken);
		fastPayTokenParamters.setPlanId(planId);
		fastPayTokenParamters.setCycleMatchType(cycleMatchType);
		fastPayTokenParamters.setInvitationCode(invitationCode);
		fastPayTokenParamters.setBuyAmount(buyAmount);
		String paramterJson = JsonUtil.getJsonStringFromObject(fastPayTokenParamters);
		
		
		PayParamtersTemp paramtersBean = new PayParamtersTemp();
		paramtersBean.setCreate_per(userId);
		paramtersBean.setParameter_str(paramterJson);
		paramtersBean.setPlatform_en_name(platform);
		paramtersBean.setReq_orderid(orderId);
		paramtersBean.setUpdate_per(userId);
		payDao.addPayParameter(paramtersBean);

		resMap.put("orderId", orderId);
		
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}

	@Override
	public PayParamtersTemp getPayParameter(Map<String, String> map)
			throws Exception {
		return payDao.getPayParameter(map);
	}

	/**
	 * 支付通快捷支付短信验证码重发主业务处理
	 */
	@Override
	public Map<String,String> dealFastPayReSend(Map<String, String> map) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		
		// 获取购买参数
		PayParamtersTemp payParamtersTemp = getPayParameter(map);
		if (payParamtersTemp == null) {
			logger.error("支付通快捷支付短信验证码重发处理中获取购买参数失败");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resMap;
		}
		
		FastPayTokenParamters reSendParamters = (FastPayTokenParamters) JsonUtil
				.getObjectFromJsonString(
						payParamtersTemp.getParameter_str(),
						FastPayTokenParamters.class);
		
		Map<String, String> payParamMap = new HashMap<String, String>();
		payParamMap.put("tradeOrderId", map.get("orderId"));// 流水号
		payParamMap.put("trDt", reSendParamters.getTrDt());// 交易时间
		payParamMap.put("fastPayToken", reSendParamters.getFastPayToken());// 平台验证码
		
//		String param = CommonUtil.getHttpParameterFromMap(payParamMap);
//		logger.debug("支付通快捷支付短信验证码重发请求参数："+param);
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(payParamMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("reSendUrl");

		String reSendResult = CommonUtil.sendPostByHttp(url, requestParam);
		
		if( null == reSendResult ){
			logger.error("支付通快捷支付短信验证码重发失败");
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message","验证码重发失败");
			return resMap;
		}else{
			//解析发送结果
			Map reSendMap = JsonUtil.getMapFromJsonString(reSendResult);
			if(null == reSendMap  || "sysException".equals(reSendMap.get("rescode"))){
				// 系统异常
				logger.error("支付通快捷支付短信验证码重发失败:" + String.valueOf(reSendMap.get("resmsg_cn")));
				resMap.put("code", Consts.ERROR_CODE);
				resMap.put("message", "验证码重发失败");
				return resMap;
			}else if("BusinessException".equals(reSendMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("支付通快捷支付短信验证码重发失败:" + String.valueOf(reSendMap.get("resmsg_cn")));
				resMap.put("code", "CHECK_CODE");
				resMap.put("message", String.valueOf(reSendMap.get("resmsg_cn")));
				return resMap;
			}else{
				resMap.put("code", Consts.SUCCESS_CODE);
				resMap.put("message", Consts.SUCCESS_DESCRIBE);
				return resMap;
			}
		}
	}


	/**
	 * 根据选择的银行卡选择对应的支付平台
	 */
	@Override
	public Bank getPayPlatformById(Map<String, String> map) throws Exception {
		return payDao.getPayPlatformById(map);
	}
	
	
	/**
	 * 支付通快捷支付预下单初期数据检查（仅充值）
	 */
	@Override
	public Map<String, String> rechargeTokenCheckData(Map<String, String> map)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();

		// 用户id
		String userId = map.get("userId");
		// 充值金额(元)
		String rechargeAmount = map.get("rechargeAmount");
		// 绑定银行卡id
		String backCardId = map.get("backCardId");
		String setupFlag = map.get("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的

		// 发送标识
		if(StrUtil.setupFlagCheck(setupFlag) == false){
			result.put("code", Consts.ERROR_CODE);
			result.put("message", Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return result;
		}
		
		// 程序必须参数未传入
		if (StringUtils.isBlank(userId)
				|| StringUtils.isBlank(backCardId)) {
			result.put("code", Consts.ERROR_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return result;
		}

		// 充值金额未输入
		if (StringUtils.isBlank(rechargeAmount)) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_LESSTHAN_1YUAN);
			return result;
		}

		// 充值金额检查（必须是1元以上）
		boolean flag = rechargeAmount.matches("^[0-9]*[\\.]{0,1}[0-9]{0,2}$");
		if (!flag) {
			// 输入的值为非法字符
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.MOUNT_IS_NON_STANDARD);
			return result;
		}

		// 判断用户是否实名认证
		User user = userService.getUserDetail(userId);
		if (!"1".equals(user.getIs_create_acct()) || !"Y".equals(user.getIdcard_validate())) {
			// 没有经过实名认证不能进行购买
			result.put("code", Consts.CHECK_CODE);
			result.put("message",Message.CnDescriptionExpression.AUTHENTICATION_IS_NOT);
			return result;
		}
		
		// 银行扣款金额必须大于1.01元
		BigDecimal amount = new BigDecimal(rechargeAmount);// 充值金额
		if (amount.compareTo(BigDecimal.valueOf(1.01)) == -1) {
			result.put("code", Consts.CHECK_CODE);
			result.put("message",
					Message.CnDescriptionExpression.BUYAMOUNT_IS_LESSTHAN_1YUAN);
			return result;
		}

		// 充值金额(分)
		String amount_fen = amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN).toPlainString();//金额(元转为分)
		result.put("amount_fen", amount_fen);//充值金额（分）

		result.put("code", Consts.SUCCESS_CODE);
		result.put("message", Consts.SUCCESS_DESCRIBE);
		return result;
	}
	
	/**
	 * 支付通快捷支付预下单主业务处理（仅充值）
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, readOnly = false)
	public Map<String,String> dealRechargeToken(Map<String, String> map) throws Exception {
		Map<String,String> resMap = new HashMap<String,String>();
		
		// 用户id
		String userId = map.get("userId");
		// 银行卡id
		String backCardId = map.get("backCardId");
		// 充值金额(分)
		String amountFen = map.get("amount_fen");
		// 充值金额(元)
		String rechargeAmount = map.get("rechargeAmount");

		
		// 获取交易流水号
		String orderId = centerService.setSeqCycleOrderNo();
		// 获取身份信息
		UserInfo userInfo = userService.getUserInfo(userId);
		// 根据银行卡id取得用户的银行卡信息
		HashMap<String,Object> userPayCdParam = new HashMap<String,Object>();
		userPayCdParam.put("isValid","Y");
		userPayCdParam.put("bankCardId", backCardId);
		userPayCdParam.put("userId", userId);
		userPayCdParam.put("isBinding", "Y");
		UserBankCardVo userRecePayCard =centerService.getRecePayBank(userPayCdParam);
		
		// 交易时间
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String timeString = dataFormat.format(date);
		
		// 预下单处理
		// 请求参数封装
		Map<String, String> payParamMap = new HashMap<String, String>();
		payParamMap.put("tradeOrderId", orderId);//获取交易流水号
		payParamMap.put("txAmt", amountFen);//充值金额（分）
		payParamMap.put("mobileNo", userRecePayCard.getPhone_no());// 银行预留手机号
		payParamMap.put("accNo", userRecePayCard.getCard_number());//卡号
		payParamMap.put("timeString", timeString);//交易时间
		payParamMap.put("realName", userInfo.getReal_name());//真实姓名
		payParamMap.put("idCardNo", userInfo.getId_card());//身份证号码
		
		String requestParam = "keyRandom=KEY_RANDOM";
		String publicKeyParam="";
		try {
			publicKeyParam = RSA.getPublick_Key_Encrypt(payParamMap);
			requestParam = requestParam.replace("KEY_RANDOM", URLEncoder.encode(publicKeyParam, "utf-8"));
		} catch (Exception e) {
			logger.debug("公钥加密串："+e);
		}
		
		//第三方工程请求url
		String url = ThirdPartyEnvUtil.getValue("payTokenUrl");

		String payTokenResult = CommonUtil.sendPostByHttp(url, requestParam);
		String paramStr = "";
		String fastPayToken = "";
		
		if( null == payTokenResult ){
			logger.error("支付通充值_预下单失败");
			throw new RuntimeException("充值预下单失败");
		}else{
			//解析发送结果
			Map payTokenResultMap = JsonUtil.getMapFromJsonString(payTokenResult);
			if(null == payTokenResultMap  || "sysException".equals(payTokenResultMap.get("rescode"))){
				// 系统异常
				logger.error("支付通充值_预下单失败:" + String.valueOf(payTokenResultMap.get("resmsg_cn")));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", "充值预下单失败");
				return resMap;
			}else if("BusinessException".equals(payTokenResultMap.get("rescode"))){
				// 业务异常，把错误信息提示给用户
				logger.error("支付通充值_预下单失败:" + String.valueOf(payTokenResultMap.get("resmsg_cn")));
				resMap.put("code", Consts.CHECK_CODE);
				resMap.put("message", String.valueOf(payTokenResultMap.get("resmsg_cn")));
				return resMap;
			}else{
				paramStr = String.valueOf(payTokenResultMap.get("paramStr"));
				fastPayToken = String.valueOf(payTokenResultMap.get("fastPayToken"));
			}
		}
		
		// 充值订单生成
		OrderFormRecharge orderFormRecharge = new OrderFormRecharge();
		String platform = "ZHIFUTONGPAY";
		orderFormRecharge.setAmount(new BigDecimal(rechargeAmount));// 订单金额（元）
		orderFormRecharge.setOrderform_id(orderId);// 订单号
		orderFormRecharge.setRecharge_orderform_status("WAIT_BUYER_PAY");// 等待付款
		orderFormRecharge.setUser_id(Integer.parseInt(userId));// 所属用户
		orderFormRecharge.setSend_message(paramStr);// 上送报文
		orderFormRecharge.setRechargetype("01");// 理财人类型
		orderFormRecharge.setAccounttype("01");// 个人主账户
		orderFormRecharge.setCore_status("CORE_WAIT");// 未调用核心，初始化状态
		if("2".equals(map.get("setupFlag"))){
			orderFormRecharge.setRecharge_channel("MOBILE"); //充值渠道（WEB:网站;MOBILE:移动端）
		}else{
			orderFormRecharge.setRecharge_channel("WEB"); //充值渠道（WEB:网站;MOBILE:移动端）
		}
		orderFormRecharge.setRecharge_platform(platform);//充值平台（UPAY:U付;SINAPAY:新浪支付;LIANLIANPAY:连连支付）
		centerDao.createRechargeOrder(orderFormRecharge);
		
		// 购买参数表设置
		RechargeTokenParamters rechargeTokenParamters = new RechargeTokenParamters();
		rechargeTokenParamters.setTradeOrderId(orderId);
		rechargeTokenParamters.setMerNo(ZftPayEnvUtil.getValue("partner_id"));//商户号
		rechargeTokenParamters.setTrDt(timeString);
		rechargeTokenParamters.setFastPayToken(fastPayToken);
		rechargeTokenParamters.setRechargeAmount(rechargeAmount);
		String paramterJson = JsonUtil.getJsonStringFromObject(rechargeTokenParamters);
		
		
		PayParamtersTemp paramtersBean = new PayParamtersTemp();
		paramtersBean.setCreate_per(userId);
		paramtersBean.setParameter_str(paramterJson);
		paramtersBean.setPlatform_en_name(platform);
		paramtersBean.setReq_orderid(orderId);
		paramtersBean.setUpdate_per(userId);
		payDao.addPayParameter(paramtersBean);

		resMap.put("orderId", orderId);
		
		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	
	
}
